<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>spring boot+websocket+广播式</title>
</head>
<body>
  <noscript>
      <h2 style="color:red">当前你的渣渣浏览器不支持websocket</h2>
  </noscript>
<div>
    <button id="connect" onclick="connect()">连接</button>
    <button id="disconnect" disabled="disabled" onclick="disconnect()">断开连接</button>
</div>
<div id="conversationDiv">
    <label>输入你的名字：</label><input type="text" id="name"/>
    <button id="sendName" onclick="sendName()">发送名字</button>
    <p id="response"></p>
</div>
  <script th:src="@{js/sockjs.min.js}"></script>
  <script th:src="@{js/stomp.min.js}"></script>
  <script th:src="@{js/jquery-3.3.1.min.js}"></script>
<script>
    var stompClient=null;
    function setConnected(connected) {
        document.getElementById("connect").disabled=connected;
        document.getElementById("disconnect").disabled=!connected;
        document.getElementById("conversationDiv").style.visibility=connected?"visible":"hidden";
        $('#response').html();
    }
    function connect() {
        var socket=new SockJS("/endpointYh");
        stompClient=Stomp.over(socket);
        stompClient.connect({},function (frame) {
            setConnected(true);
            alert("connected,"+frame);
            stompClient.subscribe('/topic/getResponse',function (response) {
                showResponse(JSON.parse(response.body).responseMessage)
            })
        })
    }
    
    function disconnect() {
        if(stompClient!=null){
            stompClient.disconnect();
        }
        setConnected(false);
        alert("断开成功");
    }

    function sendName() {
        var name=$("#name").val();
        stompClient.send("/web/welcome",{},JSON.stringify({'name':name}));
    }
    
    function showResponse(message) {
       var response=$("#response");
       response.html(message);
    }
</script>
</body>
</html>